const db = require('../mysql/db')
const bcrypt = require('bcryptjs')

exports.updateUser = (req,res) => {
    const userinfo = req.auth
    
    const {oldPassword,newPassword} = req.body
    if(!oldPassword || !newPassword) {
        return res.cc('密码不能为空')
    }
    if(oldPassword === newPassword) {
        return res.cc('新旧密码不能相同')
    }
    const sql = 'select * from user where username = ?'
    db.query(sql,userinfo.username,(err,result)=> {
        if(err) return res.cc(err)
        if(result.length !== 1) return res.cc('用户不存在')
        const compareResult = bcrypt.compareSync(oldPassword,result[0].password)
        if(!compareResult) return res.cc('密码错误')
        const sql = 'update user set password = ? where username = ?'
        const newPwd = bcrypt.hashSync(newPassword,10)
        db.query(sql,[newPwd,userinfo.username],(err,result)=> {
            if(err) return res.cc(err)
            if(result.affectedRows !== 1) return res.cc('更新用户信息失败')
            return res.cc('更新用户信息成功',0)
        })
    })
    
}